<template>
    <div class="page-content">
        <div class="page-header">
            <h1>系统日志</h1>
            <div class="header-actions">
                <a-tag :color="wsStatusColor" class="status-tag">
                    {{ wsStatusText }}
                </a-tag>
                <a-button @click="refreshLogs" :loading="manualLoading">手动刷新</a-button>
                <a-button type="primary" @click="toggleAutoRefresh">
                    {{ autoRefresh ? '暂停自动刷新' : '开启自动刷新' }}
                </a-button>
            </div>
        </div>

        <a-table :columns="columns" :data-source="logs" :pagination="pagination" :loading="tableLoading"
            @change="handleTableChange" />
    </div>
</template>
  
<script setup lang="ts">
import { message } from 'ant-design-vue'
// 配置页面为非 SSR（客户端渲染）
definePageMeta({
    ssr: false
})

useHead({
    title: '日志 - 系统控制台'
})
const authStore = useAuthStore()
// WebSocket 连接状态
const wsStatus = ref('disconnected') // disconnected, connecting, connected, error
const wsStatusColor = computed(() => {
    switch (wsStatus.value) {
        case 'connected': return 'green'
        case 'connecting': return 'orange'
        case 'error': return 'red'
        default: return 'default'
    }
})
const wsStatusText = computed(() => {
    switch (wsStatus.value) {
        case 'connected': return '已连接'
        case 'connecting': return '连接中'
        case 'error': return '连接错误'
        default: return '未连接'
    }
})

// 表格列配置
const columns = [
    { title: '时间', dataIndex: 'time', key: 'time', width: 180 },
    { title: '用户', dataIndex: 'user', key: 'user', width: 120 },
    { title: '操作', dataIndex: 'action', key: 'action' },
    { title: 'IP地址', dataIndex: 'ip', key: 'ip', width: 120 }
]

// 响应式数据
const logs = ref([])
const tableLoading = ref(false)
const manualLoading = ref(false)
const autoRefresh = ref(true) // 默认开启自动刷新
const refreshInterval = ref(300000) // 5分钟刷新一次（单位：毫秒）

// WebSocket 相关变量
let ws = null
let heartbeatTimer = null
let reconnectTimer = null
const reconnectAttempts = ref(0)
const maxReconnectAttempts = 5

// 分页配置
const pagination = reactive({
    total: 0,
    pageSize: 10,
    current: 1,
    showSizeChanger: true,
    showQuickJumper: true
})

// 初始化示例数据
const initSampleData = () => {
    logs.value = [
        { key: '1', time: '2024-01-01 10:00:00', user: 'admin', action: '用户登录系统', ip: '192.168.1.1' },
        { key: '2', time: '2024-01-01 11:00:00', user: 'admin', action: '修改系统设置', ip: '192.168.1.1' },
        { key: '3', time: '2024-01-01 12:00:00', user: 'user1', action: '查看数据报表', ip: '192.168.1.2' }
    ]
    pagination.total = logs.value.length
}

// 初始化 WebSocket 连接
const initWebSocket = () => {
    // 清理现有连接
    cleanupWebSocket()

    // 根据环境配置 WebSocket 地址
    const wsURL = process.env.NODE_ENV === 'development'
        ? 'ws://localhost:3000/ws/logs'
        : `wss://${window.location.host}/ws/logs`

    try {
        wsStatus.value = 'connecting'
        ws = new WebSocket(wsURL)

        // WebSocket 事件处理
        ws.onopen = handleWebSocketOpen
        ws.onmessage = handleWebSocketMessage
        ws.onerror = handleWebSocketError
        ws.onclose = handleWebSocketClose

    } catch (error) {
        console.error('WebSocket 初始化失败:', error)
        wsStatus.value = 'error'
    }
}

// WebSocket 打开处理
const handleWebSocketOpen = (event) => {
    console.log('WebSocket 连接已建立')
    wsStatus.value = 'connected'
    reconnectAttempts.value = 0

    // 启动心跳检测
    startHeartbeat()

    // 连接成功后立即获取一次数据
    fetchSkillsData()
}

// WebSocket 消息处理
const handleWebSocketMessage = (event) => {
    try {
        const data = JSON.parse(event.data)

        if (data.type === 'skills_list') {
            // 处理技能列表数据
            updateLogsWithSkills(data.payload)
        } else if (data.type === 'pong') {
            // 心跳响应
            console.log('心跳检测正常')
        } else if (data.type === 'error') {
            console.error('服务器返回错误:', data.message)
        }
    } catch (error) {
        console.error('消息解析错误:', error)
    }
}

// WebSocket 错误处理
const handleWebSocketError = (event) => {
    console.error('WebSocket 错误:', event)
    wsStatus.value = 'error'
}

// WebSocket 关闭处理
const handleWebSocketClose = (event) => {
    console.log('WebSocket 连接关闭:', event.code, event.reason)
    wsStatus.value = 'disconnected'

    // 清理心跳
    stopHeartbeat()

    // 自动重连逻辑
    if (reconnectAttempts.value < maxReconnectAttempts) {
        reconnectAttempts.value++
        const delay = Math.min(1000 * Math.pow(2, reconnectAttempts.value), 30000)
        console.log(`${delay}ms后尝试重连，尝试次数: ${reconnectAttempts.value}`)

        reconnectTimer = setTimeout(() => {
            initWebSocket()
        }, delay)
    }
}

// 启动心跳检测
const startHeartbeat = () => {
    // 每30秒发送一次心跳
    heartbeatTimer = setInterval(() => {
        if (ws && ws.readyState === WebSocket.OPEN) {
            ws.send(JSON.stringify({ type: 'ping' }))
        }
    }, 30000)
}

// 停止心跳检测
const stopHeartbeat = () => {
    if (heartbeatTimer) {
        clearInterval(heartbeatTimer)
        heartbeatTimer = null
    }
}

// 清理 WebSocket 资源
const cleanupWebSocket = () => {
    stopHeartbeat()

    if (reconnectTimer) {
        clearTimeout(reconnectTimer)
        reconnectTimer = null
    }

    if (ws) {
        ws.close()
        ws = null
    }
}

// 获取技能列表数据
const fetchSkillsData = async () => {
    const token = authStore.token
    const currentUser = authStore.currentUser
    if (!token || !currentUser) {
        message.error('未登录或用户信息不存在')

        return
    }
    if (!autoRefresh.value) return

    try {
        tableLoading.value = true

        // 这里替换为你的实际技能列表接口

        const response = await $fetch('/api/skills', {
            headers: {
                'Authorization': `Bearer ${token}`
            },
            query: {
                username: currentUser.username
            }
        })

        if (response.code === 200) {
            updateLogsWithSkills(response.data)
        }
    } catch (error) {
        message.error(error.data?.message || '获取技能列表失败')
    } finally {
        tableLoading.value = false
    }
}


// 使用技能数据更新日志
const updateLogsWithSkills = (skillsData) => {
    if (!skillsData || !Array.isArray(skillsData)) return

    // 将技能数据转换为日志格式
    const newLogs = skillsData.map((skill, index) => ({
        key: `skill-${Date.now()}-${index}`,
        time: new Date().toLocaleString(),
        user: 'system',
        action: `技能更新: ${skill.name || '未知技能'} - 状态: ${skill.status || '未知'}`,
        ip: '系统自动'
    }))

    // 将新日志添加到列表开头（最新日志显示在最上面）
    logs.value = [...newLogs].slice(0, 100) // 限制最多100条日志

    // 更新分页信息
    pagination.total = logs.value.length
}

// 手动刷新日志
const refreshLogs = async () => {
    manualLoading.value = true
    await fetchSkillsData()
    manualLoading.value = false
}

// 切换自动刷新
const toggleAutoRefresh = () => {
    autoRefresh.value = !autoRefresh.value

    if (autoRefresh.value) {
        // 开启自动刷新后立即获取一次数据
        fetchSkillsData()
    }
}

// 表格变化处理
const handleTableChange = (pag: any, filters: any, sorter: any) => {
    pagination.current = pag.current
    pagination.pageSize = pag.pageSize
    console.log('表格变化:', pag, filters, sorter)
}

// 生命周期
onMounted(() => {
    initSampleData()
    initWebSocket()
})

onUnmounted(() => {
    cleanupWebSocket()
})

// 监听自动刷新状态变化
watch(autoRefresh, (newVal) => {
    if (newVal) {
        fetchSkillsData()
    }
})

// 监听页面可见性变化（标签页切换时暂停/恢复）
document.addEventListener('visibilitychange', () => {
    if (document.hidden) {
        // 页面不可见时暂停自动刷新
        autoRefresh.value = false
    } else {
        // 页面可见时恢复自动刷新
        autoRefresh.value = true
    }
})
</script>
  
<style scoped>
.page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
}

.header-actions {
    display: flex;
    align-items: center;
    gap: 12px;
}

.status-tag {
    margin-right: 8px;
}

.auto-refresh-controls {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-left: 16px;
}

.interval-select {
    width: 120px;
}
</style>